var gulp = require("gulp");
var del = require("del");
var uglify = require("gulp-uglify");
var rev = require("gulp-rev");
var connect = require("gulp-connect");
var browserify = require("browserify");
var lessify = require("node-lessify");
var LessPluginAutoPrefix = require('less-plugin-autoprefix');
var lessPluginInlineUrls = require('less-plugin-base64');
var inlineUrls = new lessPluginInlineUrls({
    baseDir: 'public',
    extensions: ['svg', 'png', 'gif', /\.jpg#datauri$/i],
    maxImageSize: 8*1024, // bytes
    debug: true
});
var autoprefix = new LessPluginAutoPrefix({browsers: ["> 5%", "IE 8"]});
var tap = require("gulp-tap");
var gutil = require("gulp-util");
var sequence = require("run-sequence");
var buffer = require("vinyl-buffer");
var gulpif = require('gulp-if');
var base64 = require('gulp-base64');
var fs = require('fs');
var header = require('gulp-header');
require('colors');
var plumber = require('gulp-plumber');
var map = require('map-stream');
var sourcemaps = require("gulp-sourcemaps");
var less = require("gulp-less");
var flatten = require("gulp-flatten")
var argv = require('yargs').argv


// 生产环境打包
var jsSrc = ['resources/assets/js/app/base.js', 'resources/assets/js/app/page/*.js'];
var jsDest = 'public/app/js';
var lessSrc = ['resources/assets/less/app/*.less','resources/assets/less/app/page/*.less'];
var lessDest= 'public/app/css';

// 清理输出目录
gulp.task("clean:js", function (cb) {
    del.sync([jsDest]);
    cb(null);
});

gulp.task("clean:less", function (cb) {
    del.sync([lessDest]);
    cb(null);
});

var errorHandler = function(e){
    process.stdout.write('\x07');
    console.log(e.message.red);
}


//  打包 Js,Less
//  Less 文件使用 Js 加载
//  小图片内联到 css 文件
gulp.task("bundle:js", function (cb) {

    var stream = gulp.src(jsSrc)
        .pipe(map(function (file, cb) {

            gutil.log('bundling ' + file.path);
            var b = browserify(file.path, {
                debug: !argv.product
            });

            b.bundle(function(err, buf){
                if(err === null){
                    file.contents = buf;
                    cb(null, file)
                }else{
                    errorHandler(err);
                    cb(null, file)
                }
            });
        }))
        .pipe(gulpif(argv.product, buffer()))
        .pipe(gulpif(!argv.product, header(fs.readFileSync('./liveload.js', 'utf8'))))
        .pipe(gulpif(argv.product, uglify()))
        .pipe(gulpif(argv.product, rev()))
        .pipe(gulp.dest(jsDest))
        .pipe(gulpif(!argv.product, connect.reload()))
        .pipe(gulpif(argv.product, rev.manifest()))
        .pipe(gulp.dest(jsDest));

    return stream;
});

gulp.task("bundle:less", function () {
    gulp.src(lessSrc)
        .pipe(plumber({errorHandler: errorHandler}))
        .pipe(sourcemaps.init())
        .pipe(less({
            relativeUrls: true,
            plugins: [autoprefix, inlineUrls]
        }))
        .pipe(sourcemaps.write())
        .pipe(flatten())
        .pipe(gulp.dest(lessDest))
        .pipe(connect.reload());
});

gulp.task("watch", function (cb) {
    connect.server({
        root: "public",
        livereload: true
    });

    gulp.watch(["resources/**/*.less"], function(){
        sequence("clean:less", "bundle:less");
    });

    gulp.watch(["resources/**/*.js"], function(){
        sequence("clean:js", "bundle:js");
    });

    gulp.watch(["resources/**/*.php"], function(){
        gulp.src('public/app/**/*').pipe(connect.reload());
    });
});

gulp.task("bundle", function (cb) {
    sequence("clean:js",'clean:less', "bundle:js", "bundle:less", cb);
});

gulp.task('default', ['bundle']);

gulp.task("default", function (cb) {
    var task = ['bundle'];

    if(!argv.product)
        task.push('watch')

    sequence(task);
});

